<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑商品' : '添加商品' }}</span>
      </div>

      <el-form ref="productForm" :model="productForm" :rules="rules" label-width="120px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品编号" prop="productNumber">
              <el-input v-model="productForm.productNumber" placeholder="请输入商品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="productForm.sort" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="productForm.brandId" placeholder="请选择品牌" style="width: 100%">
                <el-option v-for="item in brandOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="categoryId">
              <el-cascader v-model="productForm.categoryId" :show-all-levels="false" :options="categoryOptions"
                style="width: 100%" placeholder="请选择分类" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="主图" prop="mainPic">
              <SingleUpload :value="productForm.mainPic" @input="handleInputMainPic"></SingleUpload>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 状态设置 -->
        <el-divider content-position="left">状态设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="上架状态">
              <el-switch v-model="productForm.publishStatus" :active-value="1" :inactive-value="0" active-text="上架"
                inactive-text="下架" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="新品状态">
              <el-switch v-model="productForm.newStatus" :active-value="1" :inactive-value="0" active-text="是"
                inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="推荐状态">
              <el-switch v-model="productForm.recommandStatus" :active-value="1" :inactive-value="0" active-text="推荐"
                inactive-text="不推荐" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务保证">
              <el-select v-model="productForm.serviceIds" :collapse-tags="true" multiple placeholder="请选择服务"
                style="width: 100%">
                <el-option label="7天无理由退货" value="1" />
                <el-option label="正品保证" value="2" />
                <el-option label="极速退款" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品规格 -->
        <div style="margin-bottom: 10px;">
          <el-divider content-position="left">商品规格</el-divider>
          <el-button type="primary" size="mini" @click="addGroup">添加规格组</el-button>
        </div>

        <div v-for="(group, groupIndex) in productForm.productGroupList" :key="groupIndex" class="group-item">
          <el-card class="box-card" style="margin-bottom: 20px">
            <div slot="header" class="clearfix">
              <span>规格组 {{ groupIndex + 1 }}</span>
              <el-button v-if="productForm.productGroupList.length > 1" style="float: right; padding: 3px 0" type="text"
                @click="removeGroup(groupIndex)">删除</el-button>
            </div>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="属性类型" :rules="{ required: true, message: '请选择属性类型', trigger: 'change' }"
                  :prop="`productGroupList.${groupIndex}.attributeCategoryId`">
                  <el-select @change="handleProductAttrChange(group.attributeCategoryId, groupIndex)"
                    v-model="group.attributeCategoryId" placeholder="请选择属性类型" style="width: 100%">
                    <el-option v-for="item in attributeCategoryOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="规格名称" :prop="`productGroupList.${groupIndex}.name`"
                  :rules="{ required: true, message: '请输入规格名称', trigger: 'blur' }">
                  <el-input v-model="group.name" placeholder="请输入规格名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 商品规格属性 -->
            <el-divider content-position="left">商品规格属性</el-divider>
            <div v-for="(productAttr, idx) in group.selectProductAttr" :key="idx" style="margin-bottom: 10px;">
              <span style="font-size: 14px;">{{ productAttr.name }}：</span>
              <el-checkbox-group v-model="group.selectProductAttr[idx].values">
                <div v-for="(item, index) in group.selectProductAttr[idx].options" :key="index"
                  style="display: inline-block" class="littleMarginLeft">
                  <el-checkbox :label="item" :key="item"></el-checkbox>
                  <el-button type="text" class="littleMarginLeft"
                    @click="handleRemoveProductAttrValue(idx, index, groupIndex)">删除</el-button>
                </div>
              </el-checkbox-group>
              <el-input size="mini" v-model="productAttr.addProductAttrValue" style="width: 160px;margin-left: 10px"
                clearable></el-input>
              <el-button size="mini" class="littleMarginLeft"
                @click="handleAddProductAttrValue(idx, groupIndex,productAttr)">增加</el-button>
            </div>
            <el-button @click="refreshSku(groupIndex, group.selectProductAttr)" type="success"
              size="mini">刷新SKU列表</el-button>

            <el-form-item :prop="`productGroupList.${groupIndex}.album`" label="规格图片">
              <multi-upload v-model="group.album"></multi-upload>
            </el-form-item>
            <el-form-item label="商品详情">
              <tinymce :width="595" :height="300" v-model="group.detail"></tinymce>
            </el-form-item>

            <!-- SKU库存列表 -->
            <el-divider content-position="left">SKU库存</el-divider>
            <el-table :data="group.skuStockList" border style="width: 100%">
              <el-table-column v-for="(attr, attrIndex) in group.selectProductAttr" :key="attrIndex" :label="attr.name"
                align="center">
                <template slot-scope="scope">
                  {{ getSkuAttribute(scope.row, attrIndex) }}
                </template>
              </el-table-column>
              <el-table-column label="SKU编号" width="120" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.skuCode"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="价格" width="120" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存" width="120" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.stock"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存预警值" width="120" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.lowStock"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="促销类型" min-width="260" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.promotionType" @change="handlePromotionTypeChange(scope.row)"
                    placeholder="请选择" size="mini">
                    <el-option label="无促销" :value="0" />
                    <el-option label="阶梯价格" :value="1" />
                    <el-option label="满减价格" :value="2" />
                  </el-select>
                  <el-button v-if="scope.row.promotionType === 1" @click="handleAddProductSkuLadder(scope.row)"
                    type="primary" size="mini">增加阶梯价格</el-button>
                  <el-button v-if="scope.row.promotionType === 2" @click="handleAddProductSkuFullReduction(scope.row)"
                    type="primary" size="mini">增加满减价格</el-button>
                  <div v-if="scope.row.promotionType === 1" class="sku-item">
                    <div v-for="(ladder, ladderIndex) in scope.row.productLadderList" :key="ladderIndex"
                      class="ladder-item">
                      <el-row :gutter="20">
                        <el-col :span="8">
                          <span>数量 </span>
                          <span><el-input v-model="ladder.count" :min="1" style="width: 100px" /></span>
                        </el-col>
                        <el-col :span="8">
                          <span>折扣 </span>
                          <span> <el-input v-model="ladder.discount" :min="0" :max="1" :precision="2"
                              style="width: 100px" /></span>
                        </el-col>
                        <el-col :span="8">
                          <el-button v-if="scope.row.productLadderList.length > 1" type="danger" icon="el-icon-delete"
                            @click="removeLadder(scope.row, ladderIndex)" />
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                  <div v-if="scope.row.promotionType === 2" class="sku-item">
                    <div v-for="(reduction, reductionIndex) in scope.row.productFullReductionList" :key="reductionIndex"
                      class="reduction-item">
                      <el-row :gutter="20">
                        <el-col :span="8">
                          <span>满金额</span>
                          <span><el-input v-model="reduction.fullPrice" :min="0" :precision="2"
                              style="width: 100px" /></span>
                        </el-col>
                        <el-col :span="8">
                          <span>减金额</span>
                          <span><el-input v-model="reduction.reducePrice" :min="0" :precision="2"
                              style="width: 100px" /></span>
                        </el-col>
                        <el-col :span="8">
                          <el-button v-if="scope.row.productFullReductionList.length > 1" type="danger"
                            icon="el-icon-delete" @click="removeReduction(scope.row, reductionIndex)" />
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="removeSku(scope.$index, groupIndex)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" @click="addSku(groupIndex)" style="margin-top: 20px">增加SKU</el-button>
          </el-card>
        </div>

        <el-form-item style="text-align: center">
          <el-button type="primary" @click="handleNext">完成</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { fetchListWithChildren } from '@/api/productCate'
import { fetchList as fetchProductAttrCateList } from '@/api/productAttrCate'
import { fetchList as fetchProductAttrList } from '@/api/productAttr'
import { updateProduct, getProduct } from '@/api/product'
import { fetchList as fetchBrandList } from '@/api/brand'
import SingleUpload from '@/components/Upload/singleUpload'
import MultiUpload from '@/components/Upload/multiUpload'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'edit',
  components: {
    SingleUpload,
    MultiUpload,
    Tinymce
  },
  data() {
    return {
      isEdit: true,
      productForm: {
        id: null,
        brandId: null,
        categoryId: null,
        productNumber: '',
        name: '',
        mainPic: '',
        sort: 0,
        publishStatus: 0,
        newStatus: 0,
        recommandStatus: 0,
        serviceIds: [],
        attributeCategoryId: null,
        productGroupList: [
          {
            name: '',
            detail: '',
            album: [],
            attributeCategoryId: null,
            selectProductAttr: [],
            skuStockList: []
          }
        ]
      },
      brandOptions: [],
      categoryOptions: [],
      attributeCategoryOptions: [],
      addProductAttrValue: '',
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        productNumber: [{ required: true, message: '请输入商品编号', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
      }
    }
  },
  created() {
    this.loadBrandOptions()
    this.loadCategoryOptions()
    this.loadAttributeCategoryOptions()

    if (this.isEdit) {
      this.loadProductDetail()
    }
  },
  methods: {

    // 添加阶梯价格
    addLadder(groupIndex, skuIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList[skuIndex].productLadderList.push({
        count: 1,
        discount: 1
      })
    },

    // 删除阶梯价格
    removeLadder(row, ladderIndex) {
      console.log("row", row)
      row.productLadderList.splice(ladderIndex, 1)
    },

    // 添加满减价格
    addReduction(groupIndex, skuIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList[skuIndex].productFullReductionList.push({
        fullPrice: 0,
        reducePrice: 0
      })
    },

    // 删除满减价格
    removeReduction(row, reductionIndex) {
      console.log("row", row)
      row.productFullReductionList.splice(reductionIndex, 1)
    },

    handlePromotionTypeChange(row) {
      row.productLadderList = []
      row.productFullReductionList = []
      console.log("促销类型", row)
    },
    handleAddProductSkuFullReduction(row) {
      row.productFullReductionList.push({
        fullPrice: 0,
        reducePrice: 0
      })
    },
    handleAddProductSkuLadder(row) {
      row.productLadderList.push({
        count: 1,
        discount: 1
      })
    },
    async loadProductDetail() {
      const productId = this.$route.params.id
      if (!productId) return
      try {
        const response = await getProduct(productId)
        console.log("----------response", response)
        const productData = response.data
        console.log("----------productData", productData)
        // 处理基础数据
        this.productForm = {
          ...productData,
          mainPic: productData.mainPic || '',
          serviceIds: productData.serviceIds ? productData.serviceIds.split(',') : [],
          categoryId: productData.categoryIdPath.split(',').map(id => Number(id)),
          productGroupList: productData.productGroupList || [
            {
              name: '',
              detail: '',
              album: [],
              attributeCategoryId: null,
              selectProductAttr: [],
              skuStockList: []
            }
          ]
        }

        // 处理规格组数据
        for (let i = 0; i < this.productForm.productGroupList.length; i++) {
          const group = this.productForm.productGroupList[i]
          if (group.album) {
            group.album = group.album.split(',')
          }
          console.log("----------group", group)
          if (group.attributeCategoryId) {
            await this.getProductAttrList(0, group.attributeCategoryId, i)
          }
        }

        // 恢复商品属性值
        this.restoreProductAttrValues()

      } catch (error) {
        console.error('加载商品详情失败:', error)
      }
    },

    async getProductAttrList(type, cid, groupIndex) {
      if (!cid || groupIndex === undefined) return

      const param = { pageNum: 1, pageSize: 100, type: type }
      try {
        const response = await fetchProductAttrList(cid, param)
        const list = response.data.list

        if (type === 0) {
          this.$set(this.productForm.productGroupList[groupIndex], 'selectProductAttr', [])

          for (let i = 0; i < list.length; i++) {
            let options = []
            let values = []

            if (this.isEdit) {
              if (list[i].handAddStatus === 1) {
                options = this.getEditAttrOptions(list[i].id, groupIndex)
              }
              values = this.getEditAttrValues(i, groupIndex)
            }

            this.productForm.productGroupList[groupIndex].selectProductAttr.push({
              id: list[i].id,
              name: list[i].name,
              handAddStatus: list[i].handAddStatus,
              inputList: list[i].inputList,
              values: values,
              options: options
            })
          }
        }
      } catch (error) {
        console.error('获取商品属性失败:', error)
      }
    },

    restoreProductAttrValues() {
      this.productForm.productGroupList.forEach((group, groupIndex) => {
        const skuStockList = group.skuStockList || []

        if (skuStockList.length > 0 && group.selectProductAttr && group.selectProductAttr.length > 0) {
          const attrMap = new Map()

          skuStockList.forEach(sku => {
            if (sku.spData) {
              try {
                const spDataArray = JSON.parse(sku.spData)
                spDataArray.forEach(item => {
                  if (!attrMap.has(item.key)) {
                    attrMap.set(item.key, new Set())
                  }
                  attrMap.get(item.key).add(item.value)
                })
              } catch (error) {
                console.error('解析spData失败:', sku.spData, error)
              }
            }
          })

          group.selectProductAttr.forEach(attr => {
            const values = attrMap.get(attr.name)
            if (values) {
              attr.values = Array.from(values)
              attr.options = Array.from(values)
            }
          })
        }
      })
    },

    getEditAttrOptions(productAttributeId, groupIndex) {
      const options = []
      const group = this.productForm.productGroupList[groupIndex]

      // 从SKU数据中提取属性值作为选项
      if (group.skuStockList) {
        const attrMap = new Map()

        group.skuStockList.forEach(sku => {
          if (sku.spData) {
            try {
              const spData = JSON.parse(sku.spData)
              spData.forEach(item => {
                if (!attrMap.has(item.key)) {
                  attrMap.set(item.key, new Set())
                }
                attrMap.get(item.key).add(item.value)
              })
            } catch (error) {
              console.error('解析spData失败:', sku.spData, error)
            }
          }
        })

        group.selectProductAttr.forEach((attr, index) => {
          if (attr.id === productAttributeId) {
            const values = attrMap.get(attr.name)
            if (values) {
              options.push(...values)
            }
          }
        })
      }

      return [...new Set(options)]
    },

    getEditAttrValues(index, groupIndex) {
      const values = new Set()
      const group = this.productForm.productGroupList[groupIndex]

      if (group.skuStockList) {
        group.skuStockList.forEach(sku => {
          if (sku.spData) {
            try {
              const spData = JSON.parse(sku.spData)
              if (spData && spData.length > index) {
                values.add(spData[index].value)
              }
            } catch (error) {
              console.error('解析spData失败:', sku.spData, error)
            }
          }
        })
      }

      return Array.from(values)
    },

    handleProductAttrChange(value, groupIndex) {
      if (value) {
        this.getProductAttrList(0, value, groupIndex)
      }
    },

    handleAddProductAttrValue(index, groupIndex,item) {
      if (!item.addProductAttrValue) {
        this.$message({ message: '属性值不能为空', type: 'warning' })
        return
      }

      const attr = this.productForm.productGroupList[groupIndex].selectProductAttr[index]
      if (!attr.options.includes(item.addProductAttrValue)) {
        attr.options.push(item.addProductAttrValue)
      }
      if (!attr.values.includes(item.addProductAttrValue)) {
        attr.values.push(item.addProductAttrValue)
      }
      item.addProductAttrValue = ''
    },

    handleRemoveProductAttrValue(index, valueIndex, groupIndex) {
      const attr = this.productForm.productGroupList[groupIndex].selectProductAttr[index]
      const value = attr.options[valueIndex]

      attr.options.splice(valueIndex, 1)
      const valueIdx = attr.values.indexOf(value)
      if (valueIdx > -1) {
        attr.values.splice(valueIdx, 1)
      }
    },

    refreshSku(groupIndex, selectProductAttr) {
      this.$confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.refreshProductSkuList(groupIndex, selectProductAttr)
      })
    },

    refreshProductSkuList(groupIndex, selectProductAttr) {
      let skuList = []

      if (!selectProductAttr || selectProductAttr.length === 0) return

      // 生成所有可能的属性组合
      const combinations = this.generateCombinations(selectProductAttr)

      combinations.forEach(combination => {
        const spData = combination.map((value, index) => ({
          key: selectProductAttr[index].name,
          value: value
        }))

        skuList.push({
          skuCode: '',
          keywords: '',
          price: 0,
          length: 0,
          width: 0,
          height: 0,
          weight: 0,
          stock: 0,
          lowStock: 0,
          promotionType: 0,
          spData: JSON.stringify(spData),
          productLadderList: [{ count: 1, discount: 1 }],
          productFullReductionList: [{ fullPrice: 0, reducePrice: 0 }]
        })
      })

      this.$set(this.productForm.productGroupList[groupIndex], 'skuStockList', skuList)
    },

    generateCombinations(selectProductAttr) {
      const result = []
      const values = selectProductAttr.map(attr => attr.values)

      function backtrack(current, index) {
        if (index === values.length) {
          result.push([...current])
          return
        }

        for (let i = 0; i < values[index].length; i++) {
          current.push(values[index][i])
          backtrack(current, index + 1)
          current.pop()
        }
      }

      backtrack([], 0)
      return result
    },

    getSkuAttribute(sku, attrIndex) {
      if (!sku.spData) return ''
      try {
        const spData = JSON.parse(sku.spData)
        return spData[attrIndex] ? spData[attrIndex].value : ''
      } catch (error) {
        return ''
      }
    },

    addGroup() {
      this.productForm.productGroupList.push({
        name: '',
        detail: '',
        album: [],
        attributeCategoryId: null,
        selectProductAttr: [],
        skuStockList: []
      })
    },

    removeGroup(index) {
      this.productForm.productGroupList.splice(index, 1)
    },

    addSku(groupIndex) {
      const sku = {
        skuCode: '',
        keywords: '',
        price: 0,
        length: 0,
        width: 0,
        height: 0,
        weight: 0,
        stock: 0,
        lowStock: 0,
        promotionType: 0,
        spData: '',
        productLadderList: [{ count: 1, discount: 1 }],
        productFullReductionList: [{ fullPrice: 0, reducePrice: 0 }]
      }
      this.productForm.productGroupList[groupIndex].skuStockList.push(sku)
    },

    removeSku(index, groupIndex) {
      this.productForm.productGroupList[groupIndex].skuStockList.splice(index, 1)
    },

    async loadBrandOptions() {
      const response = await fetchBrandList({ pageNum: 1, pageSize: 100 })
      this.brandOptions = response.data.list.map(item => ({
        value: item.id,
        label: item.name
      }))
    },

    loadCategoryOptions() {
      fetchListWithChildren().then(response => {
        let list = response.data;
        this.categoryOptions = [];
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ label: list[i].children[j].name, value: list[i].children[j].id });
            }
          }
          this.categoryOptions.push({ label: list[i].name, value: list[i].id, children: children });
        }
      });
    },

    processCategoryData(data) {
      return data.map(item => ({
        value: item.id,
        label: item.name,
        children: item.children ? this.processCategoryData(item.children) : []
      }))
    },

    async loadAttributeCategoryOptions() {
      const response = await fetchProductAttrCateList({ pageNum: 1, pageSize: 100 })
      this.attributeCategoryOptions = response.data.list.map(item => ({
        value: item.id,
        label: item.name
      }))
    },

    handleInputMainPic(val) {
      this.productForm.mainPic = val
    },

    handlePrev() {
      // 上一步逻辑
    },

    async handleNext() {
      try {
        await this.$refs.productForm.validate()

        const formData = {
          ...this.productForm,
          serviceIds: this.productForm.serviceIds.join(','),
          album: this.productForm.album ? this.productForm.album.join(',') : ''
        }

        // 处理规格组数据
        formData.productGroupList = this.productForm.productGroupList.map(group => ({
          ...group,
          album: Array.isArray(group.album) ? group.album.join(',') : group.album
        }))
        formData.categoryId = this.productForm.categoryId.join(',')
        if (this.isEdit) {
          await updateProduct(formData)
          this.$message.success('更新成功')
        }

        this.$router.push('/pms/product')
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('提交失败')
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.reduction-item,
.ladder-item {
  margin-top: 5px;
}

.box-card {
  margin-bottom: 20px;
}

.clearfix {
  font-size: 16px;
  font-weight: bold;
}

.group-item {
  margin-bottom: 20px;
}

.littleMarginLeft {
  margin-left: 5px;
}
</style>